package io.renren.modules.oss.cloud;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import io.renren.common.utils.ShortUuidUtils;
import io.renren.modules.sys.service.SysConfigService;

@Service
public class LocalStorageService {
	@Autowired
	private SysConfigService sysConfigService;

	/**
	 * 保存文件到本地目录
	 * @param multipartFile
	 * @param configKey
	 * @return 文件路径
	 */
	public SavedFileInfo saveFile(MultipartFile multipartFile, String configKey) {
		if (StringUtils.isBlank(configKey)) {
			configKey = "defaultStoragePath";
		}
		SavedFileInfo ret = new SavedFileInfo();
		ret.key = ShortUuidUtils.generateShortUuid();
		ret.shortName = multipartFile.getOriginalFilename();
		
		String path = sysConfigService.getValue(configKey);
		checkDir(new File(path));
		String fileName = ret.key + "-" + ret.shortName;
		
		ret.fullPath = path + fileName;
		
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(ret.fullPath);
			//也可以用此方法multipartFile.transferTo(ret.fullPath);
			IOUtils.copy(multipartFile.getInputStream(), fos);
			return ret;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	private void checkDir(File directory) {
		if (!directory.exists()) {
			directory.mkdirs();
		}
	}
	
	/**
	 * 保存后的文件信息
	 * @author gyrx-zhanghj
	 *
	 */
	public class SavedFileInfo {
		public String key;
		
		public String shortName;
		
		public String fullPath;
		
	}
}
